package com.superzlc.vcontroller.ctrlwidget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class XButtonView extends View {

	private Paint paint;
	public XButtonView(Context context) {
		super(context);

		paint = new Paint();
		paint.setARGB(0x7f, 0xdf, 0xdf, 0xdf);
	}

	private float w, h, left, top, right, bottom;
	private float min = 0;
	private float max = 32767;
	private float rate;
	private float position;
	private float now = 0;

	public int getAsix() {
		return (int)now;
	}


	public void setWidthAndHeight(int w, int h) {
		Log.i("vjoy", "设置大小");
		this.w = w;
		this.h = h;
		left = w / 4f;
		top = h / 8f;
		right = w - left;
		bottom = h - top;
		position = left;
		rate = (max - min) / (right - left);
	}

	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		Log.i("vjoy", "自动设置大小");
		this.setWidthAndHeight(w, h);
	}

	protected void onDraw(Canvas canvas) {
		canvas.drawColor(Color.GRAY);

		paint.setARGB(0xff, 0x3f, 0xdf, 0x00);
		canvas.drawRect(left, top, right, bottom, paint);
		paint.setARGB(0x7f, 0x30, 0x30, 0x7f);
		canvas.drawRect(position - top, top + 2, position + top, bottom - 2, paint);

		paint.setARGB(255, 255, 0, 0);
		paint.setTextSize(40);
		paint.setStrokeWidth(1);
		canvas.drawText("rate：" + rate, 10, 50, paint);
		canvas.drawText("结果：" + now, 10, 100, paint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:
			now = 0;
			position = left;
			this.invalidate();
			break;
		case MotionEvent.ACTION_DOWN:
		case MotionEvent.ACTION_MOVE:
			position = event.getX();
			now = (position - left) * rate + min;
			if (now > max) {
				now = max;
				position = right;
			} else if (now < min) {
				now = min;
				position = left;
			}
			this.invalidate();
			break;
		}
		return true;
	}
}
